package com.acegear.horizon.domain.repository;

import com.acegear.horizon.domain.models.Comment;
import com.acegear.horizon.domain.models.jpa.PostComment;
import com.acegear.horizon.domain.models.vo.CommentVO;
import com.acegear.horizon.domain.repository.jpa.PostCommentRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by wangsike on 2017/2/9.
 */
@Component
public class CommentRepository {
    @Autowired
    private PostCommentRepository postCommentRepository;

    public Stream<Comment> findByPostId(Long postId, Pageable pageable) {
        return postCommentRepository
                .findByPostIdAndDeletedOrderByIdAsc(postId, false, pageable)
                .stream()
                .map(Comment::new);
    }

    public Stream<Comment> findByUserId(Long userId, Pageable pageable) {
        return postCommentRepository
                .findByUserIdAndDeletedOrderByIdAsc(userId, false, pageable)
                .stream()
                .map(Comment::new);
    }

    public Integer countByPostId(Long postId) {
        return postCommentRepository.countByPostIdAndDeleted(postId, false);
    }

    public Integer countByUserId(Long userId) {
        return postCommentRepository.countByUserIdAndDeleted(userId, false);
    }

    public Long getCurrentFloor(Long postId) {
        return postCommentRepository
                .findTopByPostIdOrderByIdDesc(postId)
                .map(PostComment::getFloor)
                .orElse(0L);
    }


    public Optional<Comment> findCommentId(Long commentId) {
        return Optional.ofNullable(postCommentRepository.findByCommentId(commentId)).map(Comment::new);
    }

    public List<CommentVO> findVOByUserIdAndPostId(Long userId, Long postId) {
        return postCommentRepository
                .findByUserIdAndPostIdOrderByIdAsc(userId, postId)
                .stream()
                .map(Comment::new)
                .map(Comment::getCommentVO)
                .collect(Collectors.toList());
    }

    public Stream<Comment> findAll() {
        return postCommentRepository.findAll().stream().map(Comment::new);
    }
}
